#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUrl>
#include <QDebug>
#include <QJsonArray>
#include <QFile>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //从文件里面读取token
    readTokenFromFile();

    // ///////////////
    HttpServer server;
    if (!server.listen(QHostAddress::Any, 8080 )) {
        qFatal("Failed to start server");
    }

    qDebug("Server started on port 8080 ");



}

MainWindow::~MainWindow()
{
    delete ui;
}

//获取IAM用户Token
void MainWindow::on_pushButton_clicked()
{
    getToken();
}


//获取IAM用户Token
void MainWindow::getToken() {
    QNetworkAccessManager *manager = new QNetworkAccessManager();

    // 假设这里是你的请求URL
    QNetworkRequest request(QUrl("https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 发送请求
    QByteArray requestBody = R"({
        "auth": {
            "identity": {
                "methods": ["password"],
                "password": {
                    "user": {
                        "name": "xiaoTang",
                        "domain": { "name": "hid_kyuemcfc6vsdleg" },
                        "password": "20030506t"
                    }
                }
            }
        }
    })";

    QNetworkReply *reply = manager->post(request, requestBody);

    QObject::connect(reply, &QNetworkReply::finished, [reply, this]() {
        if (reply->error() == QNetworkReply::NoError) {
            // 获取响应头中的 X-Subject-Token
            token = reply->rawHeader("X-Subject-Token");
            qDebug() << "Extracted Token:" << token;

            // 保存 token 到文件
            saveTokenToFile(token);

            // 可选：处理响应体
            QByteArray responseData = reply->readAll();
            QJsonDocument doc = QJsonDocument::fromJson(responseData);
            if (!doc.isNull() && doc.isObject()) {
                // 进一步处理响应数据
            }
        } else {
            qWarning() << "Network error:" << reply->errorString();
        }
        reply->deleteLater();  // 清理
    });
}


//查询IAM用户可以访问的项目列表
void MainWindow::getProjects() {
    QNetworkAccessManager *manager = new QNetworkAccessManager();

    QUrl url("https://iam.cn-north-4.myhuaweicloud.com/v3/auth/projects");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("X-Auth-Token", token);

    qDebug() << "\nToken" << token;

    QNetworkReply *reply = manager->get(request);

    QObject::connect(reply, &QNetworkReply::finished, [reply]() {
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();
            qDebug() << "Response:" << responseData;

            QJsonDocument doc = QJsonDocument::fromJson(responseData);
            if (!doc.isNull() && doc.isObject()) {
                // 处理 JSON 数据
            }
        } else {
            qWarning() << "Network error:" << reply->errorString();
        }
        reply->deleteLater();  // 清理
    });
}


//保存 token 到文件
void MainWindow::saveTokenToFile(const QByteArray &token) {
    QFile file("token.txt");
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);
        out << token;
        file.close();
        qDebug() << "Token saved to token.txt";
    } else {
        qWarning() << "Failed to open file for writing:" << file.errorString();
    }
}

//从文件里面读取token
void MainWindow::readTokenFromFile() {
    QFile file("token.txt");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        token = in.readAll().toLocal8Bit();
        file.close();
        qDebug() << "Token read from file:" << token;
    } else {
        qWarning() << "Failed to open file for reading:" << file.errorString();
    }
}


//查询IAM用户可以访问的项目列表
void MainWindow::on_pushButton_2_clicked()
{
    getProjects();
}


//创建规则触发条件，触发条件为属性上报
void MainWindow::on_pushButton_3_clicked()
{
    QString endpoint = "a86e02ef2d.st1.iotda-app.cn-north-4.myhuaweicloud.com"; // 替换为实际的 endpoint
    QString projectId = "1c983a56c120428aadc0ccc439324f7f"; // 替换为实际的 project_id

    sendPostRequest(endpoint, projectId);
}


//创建规则触发条件，触发条件为属性上报
void MainWindow::sendPostRequest(const QString &endpoint, const QString &projectId) {
    QNetworkAccessManager *manager = new QNetworkAccessManager();

    // 构建 URL
    QString urlString = QString("https://%1/v5/iot/%2/routing-rule/rules").arg(endpoint).arg(projectId);
    QUrl url(urlString);

    // 创建请求
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 添加认证头
    request.setRawHeader("X-Auth-Token", token);

    // 创建 JSON 数据
    QJsonObject json;
    json["rule_name"] = "rulename";
    json["subject"] = QJsonObject{
        {"resource", "device.property"},
        {"event", "report"}
    };
    json["app_type"] = "GLOBAL";
    json["description"] = "description";

    QJsonDocument jsonDoc(json);
    QByteArray jsonData = jsonDoc.toJson();

    // 发送 POST 请求
    QNetworkReply *reply = manager->post(request, jsonData);

    // 连接信号和槽以处理响应
    QObject::connect(reply, &QNetworkReply::finished, [reply]() {
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();
            qDebug() << "\nResponse:" << responseData;
        } else {
            qDebug() << "Error:" << reply->errorString();
        }
        reply->deleteLater();
    });
}

//查询规则条件列表
void MainWindow::on_pushButton_4_clicked()
{
    QString endpoint = "a86e02ef2d.st1.iotda-app.cn-north-4.myhuaweicloud.com"; // 替换为实际的 endpoint
    QString projectId = "1c983a56c120428aadc0ccc439324f7f"; // 替换为实际的 project_id


    sendGetRequest(endpoint, projectId);
}

void MainWindow::sendGetRequest(const QString &endpoint, const QString &projectId) {
    QNetworkAccessManager *manager = new QNetworkAccessManager();

    // 构建 URL
    QString urlString = QString("https://%1/v5/iot/%2/routing-rule/rules").arg(endpoint).arg(projectId);
    QUrl url(urlString);

    // 创建请求
    QNetworkRequest request(url);

    // 添加认证头
    request.setRawHeader("X-Auth-Token", token);

    // 发送 GET 请求
    QNetworkReply *reply = manager->get(request);

    // 连接信号和槽以处理响应
    QObject::connect(reply, &QNetworkReply::finished, [reply]() {
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();
            qDebug() << "\nResponse:" << responseData;
        } else {
            qDebug() << "\nError:" << reply->errorString();
        }
        reply->deleteLater();
    });
}


//创建规则动作
void MainWindow::on_pushButton_5_clicked()
{
    QString endpoint = "a86e02ef2d.st1.iotda-app.cn-north-4.myhuaweicloud.com"; // 替换为实际的 endpoint
    QString projectId = "1c983a56c120428aadc0ccc439324f7f"; // 替换为实际的 project_id
    ///////////////////
    QString rule_id = "31f4e292-a3eb-4810-a18e-12eb147b5647";

    sendPostRequest(endpoint, projectId, rule_id);
}

////////////////创建规则动作,这个函数还有问题
void MainWindow::sendPostRequest(const QString &endpoint, const QString &projectId, const QString rule_id) {
    QNetworkAccessManager *manager = new QNetworkAccessManager();

    // 构建 URL
    QString urlString = QString("https://%1/v5/iot/%2/routing-rule/actions").arg(endpoint).arg(projectId);
    QUrl url(urlString);

    // 创建请求
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 添加认证头
    request.setRawHeader("X-Auth-Token", token);

    // 创建 JSON 数据
    QJsonObject json;
    json["rule_id"] = rule_id; // 替换为实际的 rule_id
    json["channel"] = "HTTP_FORWARDING";

    QJsonObject httpForwarding;
    httpForwarding["url"] = "http://192.168.248.128:8080"; // 替换为实际的 URL

    QJsonObject channelDetail;
    channelDetail["http_forwarding"] = httpForwarding;

    json["channel_detail"] = channelDetail;

    QJsonDocument jsonDoc(json);
    QByteArray jsonData = jsonDoc.toJson();

    // 发送 POST 请求
    QNetworkReply *reply = manager->post(request, jsonData);

    // 连接信号和槽以处理响应
    QObject::connect(reply, &QNetworkReply::finished, [reply]() {
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();
            qDebug() << "Response:" << responseData;
        } else {
            qDebug() << "Error:" << reply->errorString();
        }
        reply->deleteLater();
    });
}

//查询设备影子数据
void MainWindow::on_pushButton_6_clicked()
{
    // 替换为实际的 endpoint、project_id 和 device_id
    QString endpoint = "a86e02ef2d.st1.iotda-app.cn-north-4.myhuaweicloud.com";
    QString projectId = "1c983a56c120428aadc0ccc439324f7f";
    QString deviceId = "66e92a9dfeb1bf7f7917fe52_test2";

    fetchDeviceShadow(endpoint, projectId, deviceId);
}

//查询设备影子数据
void MainWindow::fetchDeviceShadow(const QString &endpoint, const QString &projectId, const QString &deviceId) {
    QNetworkAccessManager *networkManager = new QNetworkAccessManager();

    QString url = QString("https://%1/v5/iot/%2/devices/%3/shadow")
                      .arg(endpoint)
                      .arg(projectId)
                      .arg(deviceId);

    QNetworkRequest request((QUrl(url)));
    request.setRawHeader("X-Auth-Token", token);

    QNetworkReply *reply = networkManager->get(request);

    QObject::connect(reply, &QNetworkReply::finished, [reply]() {
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << "Error:" << reply->errorString();
        } else {
            QString response = reply->readAll();
            qDebug() << "Response:" << response;
        }
        reply->deleteLater(); // 清理

    });
}
